using System;
using System.Collections.Generic;
using System.Drawing;

using SharpWind.Input;

namespace SharpWind.Gui.Controls
{
	public class RadioButtonGroup : Control
	{
		private List<RadioButton> radioButtons = new List<RadioButton>();

		private RadioButton lastChanged = null;

		public RadioButtonGroup()
		{
			Size = new SizeF( 85, 55 );
		}

		public void Add( RadioButton radioButton )
		{
			radioButton.Location = new PointF( radioButton.Location.X + Location.X, radioButton.Location.Y + Location.Y );
			radioButton.CheckedChanged += new EventHandler( OnRadioButtonCheckedChanged );
			this.radioButtons.Add( radioButton );
		}

		public void Remove( RadioButton radioButton ) {}

		public void RemoveAll()
		{
			this.radioButtons.Clear();
		}

		private void OnRadioButtonCheckedChanged( object sender, EventArgs e )
		{
			RadioButton radioButton = sender as RadioButton;
			if( radioButton != null && lastChanged != radioButton )
			{
				foreach( RadioButton rb in this.radioButtons )
				{
					if( rb != radioButton )
					{
						this.lastChanged = rb;
						rb.Checked = false;
					}
				}

				this.lastChanged = null;
			}
		}

		internal override void MouseDown( MouseEventArgs e )
		{
			if( Visible && Enabled )
			{
				foreach( RadioButton rb in this.radioButtons )
				{
					rb.MouseDown( e );
				}
			}
		}

		internal override void MouseMove( MouseEventArgs e )
		{
			if( Visible && Enabled )
			{
				foreach( RadioButton rb in this.radioButtons )
				{
					rb.MouseMove( e );
				}
			}
		}

		internal override void MouseUp( MouseEventArgs e )
		{
			if( Visible && Enabled )
			{
				foreach( RadioButton rb in this.radioButtons )
				{
					rb.MouseUp( e );
				}
			}
		}

		internal override void Render()
		{
			if( Visible )
			{
				foreach( RadioButton rb in this.radioButtons )
				{
					if( rb.Location.X + rb.Size.Width < Location.X + Size.Width &&
					    rb.Location.Y + rb.Size.Height < Location.Y + Size.Height )
					{
						rb.Render();
					}
				}
			}
		}

		public override PointF Location
		{
			get
			{
				return this.location;
			}
			set
			{
				if( this.location != value )
				{
					float x = value.X - this.location.X;
					float y = value.Y - this.location.Y;

					this.location = value;

					foreach( RadioButton rb in this.radioButtons )
					{
						rb.Location = new PointF( rb.Location.X + x, rb.Location.Y + y );
					}
				}
			}
		}
	}
}